package com.suning.sncfc.presenter;

import android.content.Context;
import android.text.TextUtils;


import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.sjtu.gson.JsonObject;
import com.sncfc.commlayer.PreferenceUtil;
import com.sncfc.commlayer.TLog;
import com.suning.sncfc.MainActivity;
import com.suning.sncfc.MainApplication;
import com.suning.sncfc.app.Global;
import com.suning.sncfc.ui.common.BaseModel;
import com.suning.sncfc.ui.common.BasePresenter;
import com.suning.sncfc.ui.common.BaseView;
import com.suning.sncfc.ui.common.UserHandler;

import com.suning.sncfc.util.CommonUtils;
import com.suning.sncfc.util.JSONUtil;

import com.suning.sncfc.util.ToastUtil;
import com.suning.sncfc.util.UniqueIDUtil;
import com.suning.sncfc.util.ZipUtils;
import com.suning.sncfc.util.encrypt_old.MD5Util;
import com.suning.sncfc.util.http.HttpConfig;
import com.suning.sncfc.util.http.ResponseListener2;
import com.suning.sncfc.util.http.SNCFCRequest2;
import com.suning.sncfc.util.http.filter.DefaultRequestFilter;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;

import static com.suning.sncfc.util.http.SNCFCRequest2.sendRequest;

public class RnUpgradePresenter  {

    private final RnUpgradeModel model;
    private Context context;

    public RnUpgradePresenter(Context context) {
        this.context=context;
        model = new RnUpgradeModel();
    }

    /**
     * 查询热更新
     */
    public void isRnUpGrade( ){
        model.isRNUpGrade(new ResponseListener2() {
            @Override
            public void onSucceed(String code, String msg, JSONObject object) {
                if ("0000".equals(code)){
                    JSONObject jsonObject = JSONUtil.getJSONObject(object,"data");
                  String rnBundleVersion=  JSONUtil.getString(jsonObject,"rnBundleVersion");
                    String upgradeAddress=  JSONUtil.getString(jsonObject,"downloadUrl");
                    String versionId=  JSONUtil.getString(jsonObject,"versionId");
                    String bundleFileMd5=  JSONUtil.getString(jsonObject,"bundleFileMd5");
                    boolean isUpdate = JSONUtil.getBoolean(jsonObject,"isUpdate");
                    PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSIONID,versionId,context);
                    if (isUpdate){
                        TLog.d("热更新： "+isUpdate+"----"+rnBundleVersion);
                        PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSIONNEW,rnBundleVersion,context);
                        if (UniqueIDUtil.getVersionName().equals(rnBundleVersion)){
                            TLog.d("热更新： "+"版本号相同，不下载");
                            TLog.d("热更新： "+rnBundleVersion);
                        }else {
                         String hotfixpath =   PreferenceUtil.getString(PreferenceUtil.HOTFIXPATH,context);
                         TLog.d("hotfixpath"+hotfixpath);
                            TLog.d("热更新： "+"版本号不相同");
                         File hotfixFile = new File(Global.HOTFIXPATH+"/snc_rn_android_"+rnBundleVersion+"/"+Global.JS_BUNDLE_LOCAL_FILE);
                            String md5 = MD5Util.getFileMD5(hotfixFile);
                                if (hotfixFile.exists()&&hotfixFile.isFile()&&md5!=null&&(bundleFileMd5.equals(md5)||bundleFileMd5.equals(md5.toUpperCase()))){

                                    TLog.d("热更新： "+"文件存在，MD5相同，不下载");
                                   // PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSION,rnBundleVersion,context);
                                }else {
                                    TLog.d("热更新： "+"文件不存在，下载");
                                   // CommonUtils.deleteFileDirectory(new File(Global.HOTFIXPATH));
                                    TLog.d("热更新： "+"md5不一致删除");
                                    //if (TextUtils.isEmpty(hotfixpath)||!(Global.HOTFIXPATH+"/snc_rn_android_"+rnBundleVersion).equals(hotfixpath)){
                                        startDownload(upgradeAddress,bundleFileMd5,rnBundleVersion,versionId);
                                        TLog.d("热更新： "+"下载");
                                  //  }
                                }


                        }


                    }

                }
            }

            @Override
            public void onFailed(String reason, String msg) {

            }
        });
    }

    /**
     * 更新下载次数
     * @param isSuccess
     * @param rnBundleVersion
     * @param versionId
     */
    public void upgradeRnDownloadNum(final boolean isSuccess,final String rnBundleVersion,String versionId){
        model.upgradeRnDownloadNum(isSuccess,rnBundleVersion,versionId,new ResponseListener2() {
            @Override
            public void onSucceed(String code, String msg, JSONObject object) {
                TLog.i("SNCRNUPDATE    isSuccess= "+isSuccess+"  rnBundleVersion= "+rnBundleVersion);
            }

            @Override
            public void onFailed(String reason, String msg) {

            }
        });
    }

    class RnUpgradeModel extends BaseModel{
        /**
         * 查询热更新信息
         * @param listener
         */
        public void isRNUpGrade(ResponseListener2 listener) {
            String version = PreferenceUtil.getString(PreferenceUtil.HOTFIXVERSION,context);
            JSONObject object = new JSONObject();
                JSONUtil.put(object,"rnBundleVersion", TextUtils.isEmpty(version)?UniqueIDUtil.getVersionName():version);
                JSONUtil.put(object, "mobile", UserHandler.getMobile());
                JSONUtil.put(object, "terminalType", Global.TERMINALTYPE);
                sendEncryptRequest(object, HttpConfig.ISRNUPGRADE,listener);



        }

        /**
         * 更新下载次数
         * @param isSuccess
         * @param rnBundleVersion
         * @param versionId
         * @param listener
         */
        public void upgradeRnDownloadNum(boolean isSuccess,String rnBundleVersion,String versionId,ResponseListener2 listener){
            String version = PreferenceUtil.getString(PreferenceUtil.HOTFIXVERSION,context);
                JSONObject object = new JSONObject();
                JSONUtil.put(object, "rnBundleVersion", rnBundleVersion);
                 JSONUtil.put(object, "versionId", versionId);
            JSONUtil.put(object, "isSuccess", isSuccess);
                sendNormalRequest(object, HttpConfig.UPGRADERNDOWNLOADNUM,listener);


        }
    }

    /**
     * 下载
     * @param address
     * @param bundleFileMd5
     * @param rnBundleVersion
     * @param versionId
     */
    private void startDownload(final String address,final String bundleFileMd5,final String rnBundleVersion,final String versionId) {

        new Thread(){
            @Override
            public void run() {
                super.run();
                FileDownloader.getImpl().create(address).setPath(new File(Global.HOTFIXPATH).getAbsolutePath()+"/snc_rn_android_"+rnBundleVersion+".zip").setListener(new FileDownloadLargeFileListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                        TLog.d("下载进度： pending"+totalBytes);
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                        TLog.d("下载进度： "+soFarBytes);
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                        TLog.d("下载进度： paused");
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        TLog.d("下载进度： 下载成功");
                        String filePath =  new File(Global.HOTFIXPATH).getAbsolutePath() + "/snc_rn_android_" + rnBundleVersion + ".zip";
                        try {
                            int i = ZipUtils.UnZipFolder(filePath, Global.HOTFIXPATH);

                                if (1==i){

                                    String fileMD5 = MD5Util.getFileMD5(new File(Global.HOTFIXPATH + "/snc_rn_android_"+rnBundleVersion+"/"+Global.JS_BUNDLE_LOCAL_FILE));
                                    TLog._d("fileMD5",fileMD5);
                                    if (bundleFileMd5.equals(fileMD5)||bundleFileMd5.toLowerCase().equals(fileMD5)){
                                        JSONObject object= new JSONObject();
                                        JSONUtil.put(object,"下载地址","地址 :"+address);
                                        JSONUtil.put(object,"更新版本","版本号 :"+rnBundleVersion);
                                        ZhugeSDK.getInstance().track(MainApplication.getInstance(),"RN热更新-下载成功",object);
                                        //PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSION,rnBundleVersion,context);
                                        PreferenceUtil.putString(rnBundleVersion,bundleFileMd5,context);
                                        PreferenceUtil.putString(PreferenceUtil.HOTFIXPATH,Global.HOTFIXPATH+"/snc_rn_android_"+rnBundleVersion,context);
                                        upgradeRnDownloadNum(true,rnBundleVersion,versionId);
                                    }else {
                                        JSONObject object= new JSONObject();
                                        JSONUtil.put(object,"下载地址","地址 :"+address);
                                        JSONUtil.put(object,"原因","原因：Md5不一致");
                                        ZhugeSDK.getInstance().track(MainApplication.getInstance(),"RN热更新-下载失败",object);
                                        TLog.e("下载： MD5不一致");
                                        CommonUtils.deleteFileDirectory(new File(Global.HOTFIXPATH));
                                        PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSIONNEW,"",context);
                                        PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSION,"",context);
                                        upgradeRnDownloadNum(false,rnBundleVersion,versionId);

                                    }
                                }else {
                                    CommonUtils.deleteFileDirectory(new File(Global.HOTFIXPATH+"/snc_rn_android_"+rnBundleVersion));
                                    upgradeRnDownloadNum(false,rnBundleVersion,versionId);
                                }



                        } catch (Exception e) {
                            JSONObject object= new JSONObject();
                            JSONUtil.put(object,"下载地址","地址 :"+address);
                            JSONUtil.put(object,"原因","原因："+e);
                            ZhugeSDK.getInstance().track(MainApplication.getInstance(),"RN热更新-下载失败",object);
                            e.printStackTrace();
                            TLog.e("下载： error"+e);
                            PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSIONNEW,"",context);
                            upgradeRnDownloadNum(false,rnBundleVersion,versionId);
                        }finally {
                            File file=  new File(filePath);
                            if (file.exists()&&file.isFile()){
                                file.delete();
                            }
                        }
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        JSONObject object= new JSONObject();
                        JSONUtil.put(object,"下载地址","地址 :"+address);
                        JSONUtil.put(object,"原因","原因："+e);
                        ZhugeSDK.getInstance().track(MainApplication.getInstance(),"RN热更新-下载失败",object);
                        TLog.e("下载： error"+e);
                        PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSIONNEW,"",context);
                        upgradeRnDownloadNum(false,rnBundleVersion,versionId);
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        TLog.e("下载： warn");
                        PreferenceUtil.putString(PreferenceUtil.HOTFIXVERSIONNEW,"",context);
                        upgradeRnDownloadNum(false,rnBundleVersion,versionId);
                    }
                }).start();
            }
        }.start();
    }

}

